package com.commpany.jdq.core.common;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;




public class DateUtils {
	public static final long ONE_DAY_LONG = 86400000;
	private static DateUtils classInstance = new DateUtils();
    public static final String simpleFormat1 = "yyyy-MM-dd";
	public static final String DATE_YYYYMMDDHMS = "yyyyMMddHHmmss";
	public static final String simpleFormat2 = "yyyy年MM月dd日";
    public static final String simpleFormat3 = "yyyy-MM-dd hh:MM:SS";
    public static final String simpleFormat4 = "yyyy-MM-dd HH:MM:SS";
    public static final String DATE_YYYYMMDDHM = "yyyyMMddHHmm";



    public static DateUtils getInstance() {
		return classInstance;
	}

	public static String timestamp2string(Timestamp time, String pattern) {
		Date d = new Date(time.getTime());

		if (pattern == null) {
			pattern = "yyyy-MM-dd HH:mm:ss";
		}
		return DateFormatUtils.format(d, pattern);
	}

	public static String formatDate(Date date, String pattern) {
		if (date == null) {
			date = new Date(System.currentTimeMillis());
		}

		if (pattern == null) {
			pattern = "yyyy-MM-dd HH:mm:ss";
		}
		return DateFormatUtils.format(date, pattern);
	}

	public static String defaultFormat(Date date) {
		return formatDate(date, null);
	}

	public static Date parseDateFormat() {
		SimpleDateFormat fo = new SimpleDateFormat();
		Date date = new java.util.Date(System.currentTimeMillis());
		fo.applyPattern("yyyy-MM-dd");

		try {
			date = fo.parse(DateFormatUtils.format(date, "yyyy-MM-dd"));
		} catch (Exception e) {
		}

		return date;
	}

    public static Date parseCurrentDateFormat() {
		SimpleDateFormat fo = new SimpleDateFormat();
		Date date = new java.util.Date(System.currentTimeMillis());
		fo.applyPattern("yyyy-MM-dd");

		try {
			date = fo.parse(DateFormatUtils.format(date, "yyyy-MM-dd"));
		} catch (Exception e) {
		}

		return date;
	}

	public static String parseTimestampFormat(Timestamp time) {

		if (time != null && !time.equals("")) {

			return parseDateFormat(new Date(time.getTime()));

		} else {

			return "";
		}

	}

	public static String parseDateFormat(Date date) {
		SimpleDateFormat fo = new SimpleDateFormat();
		fo.applyPattern("yyyy-MM-dd");
		String retVal = "0000-00-00";
		try {
			retVal = DateFormatUtils.format(date, "yyyy-MM-dd");
		} catch (Exception e) {
		}

		return retVal;
	}

    	public static String parseDateFullFormat(Date date) {

		String retVal = "0000-00-00";
		try {
			retVal = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
		} catch (Exception e) {
		}

		return retVal;
	}

	/**
	 * YYYY-MM-DD
	 * 
	 * @return
	 */
	public static Timestamp formatFromYYYYMMDD(String value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(value);
		} catch (ParseException e) {
			return null;
		}
		return new Timestamp(date.getTime());
	}

	public static Date string2Date(String str) {
		if (StringUtils.isEmpty(str))
			return new Date();
		return java.sql.Date.valueOf(str);
	}

	public static boolean between(Date srcDate, Date startDate, Date endDate) {
		if (startDate.after(srcDate))
			return false;
		if (endDate.before(srcDate))
			return false;
		return true;
	}

	public static Date getDayStart(Date date) {
		return string2Date(divideDateForDay(date, "yyyy-MM-dd", 0));
		// return Timestamp.valueOf(formatDate(date, "yyyy-MM-dd")+" 00:00:00");
	}

	public static Date getDayEnd(Date date) {
		return string2Date(divideDateForDay(date, "yyyy-MM-dd", 1));
		// return Timestamp.valueOf(formatDate(date, "yyyy-MM-dd")+" 23:59:59");
	}

	public static String getDayMin(String date) {
		 return (date+" 00:00:00");
	}

	public static String getDayMax(String date) {
		 return (date+" 23:59:59");
	}

	public static String divideDateForDay(Date date, String pattern, int num) {
		if (date == null)
			date = new Date(System.currentTimeMillis());
		if (pattern == null)
			pattern = "yyyy-MM-dd HH:mm";
		Calendar cal = null;
		SimpleDateFormat fo = new SimpleDateFormat();
		fo.applyPattern(pattern);
		try {
			fo.format(date);
			cal = fo.getCalendar();
			cal.add(Calendar.DATE, num);
		} catch (Exception e) {
		}
		return fo.format(cal.getTime());
	}


	public static Date afterNDay(int n) {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, n);
		Date d2 = c.getTime();
		return d2;
	}

	public static Date afterNDays(Timestamp time, int n) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time.getTime());
		c.add(Calendar.DATE, n);
		Date d2 = c.getTime();
		return d2;
	}

	public static Timestamp transDate(Date date) {
		if (date != null) {
			long time = date.getTime();
			return new Timestamp(time);
		}
		return null;
	}

	public static Date transTimestamp(Timestamp time) {
		if (time != null) {
			long t = time.getTime();
			return new Date(t);
		}
		return null;
	}

	public static java.sql.Timestamp stringToTime1(String d) {
		java.sql.Timestamp t = null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date d1;
		try {
			if (StringUtils.isNotEmpty(d)) {
				d1 = df.parse(d);
				t = new Timestamp(d1.getTime());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return t;
	}

	public static java.sql.Timestamp stringToTime2(String d) {
		java.sql.Timestamp t = null;
		if (StringUtils.isNotEmpty(d)) {
			t = Timestamp.valueOf(d + " 23:59:59");
		}
		return t;
	}

	public static Calendar getYesterDayBegin() {
		Calendar before = Calendar.getInstance();

		before.set(Calendar.DAY_OF_MONTH,
		before.get(Calendar.DAY_OF_MONTH) - 1);
		before.set(Calendar.HOUR_OF_DAY, 0);
		before.set(Calendar.MINUTE, 0);
		before.set(Calendar.SECOND, 0);
		before.set(Calendar.MILLISECOND, 0);

		return before;
	}

	public static Calendar getYesterDayEnd() {
		Calendar after = Calendar.getInstance();
		after.set(Calendar.DAY_OF_MONTH, after.get(Calendar.DAY_OF_MONTH) - 1);
		after.set(Calendar.HOUR_OF_DAY, 23);
		after.set(Calendar.MINUTE, 59);
		after.set(Calendar.SECOND, 59);
		after.set(Calendar.MILLISECOND, 999);
		return after;
	}
	
	/**
	 * @param cal
	 * @return
	 */
	public static Timestamp transCalendarToTimestamp(Calendar cal)
	{
		Timestamp ts = new Timestamp(cal.getTimeInMillis());
		return ts;
	}

	public static String transTimestamptostr(Timestamp time) {
		if (time != null) {

			java.util.Calendar c = Calendar.getInstance();
			c.setTime(time);
			String year = String.valueOf(c.get(c.YEAR));
			String month = String.valueOf(c.get(c.MONTH) + 1);
			String day = String.valueOf(c.get(c.DATE));

			if (month.length() < 2)
				month = "0" + month;
			if (day.length() < 2)
				day = "0" + day;
			return year.substring(2, 4) + month + day;

		}
		return null;
	}
	public static String getDataString(Calendar cal)
	{
		Calendar now=cal;
		String time=now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH)+1)+"-"+now.get(Calendar.DAY_OF_MONTH)+" "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND);
		return time;
	}
	public static String parseCalendarDate(String date) {
		String d1 = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try { 
			d1 = sdf.format(sdf.parse(date));
		} catch (Exception e) {
            e.printStackTrace();
		}

		return d1;
	}

    public static String parseCalendarDate(String date,String format) {
		String d1 = null;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			d1 = sdf.format(sdf.parse(date));
		} catch (Exception e) {
            e.printStackTrace();
		}

		return d1;
	}

    public static String parseCalendarDateToFormat(String date) {
		String d1 = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String result = null;
		try {
			Date date1 = sdf.parse(date);
            long timeDiff =  System.currentTimeMillis()  - date1.getTime();
            long period=0;


            if(timeDiff / 1000 < 3600)
            {
                period = timeDiff / 1000 / 60;

                if(period < 1) period = 1;
                result = period + "分钟前";
                
            }
            else if(timeDiff / 1000 / 60 / 60 < 24)
            {
                period = timeDiff / 1000 / 60 / 60;
                result = period + "小时前";
            }
            else if(timeDiff / 1000 / 60 / 60 / 24 < 4)
            {
                period = timeDiff / 1000 / 60 / 60 /24;
                result = period + "天前";
            }
            else
            {
                	sdf = new SimpleDateFormat("yyyy-MM-dd");
                    result = sdf.format(sdf.parse(date));
            }

		} catch (Throwable e) {
            e.printStackTrace();
		}

		return result;
	}

	public static String getDateIntervalToNow(Date date) {
		String d1 = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String result = null;
		try {
			long timeDiff =  System.currentTimeMillis()  - date.getTime();
			long period=0;


			if(timeDiff / 1000 < 3600)
			{
				period = timeDiff / 1000 / 60;

				if(period < 1) period = 1;
				result = period + "分钟前";

			}
			else if(timeDiff / 1000 / 60 / 60 < 24)
			{
				period = timeDiff / 1000 / 60 / 60;
				result = period + "小时前";
			}
			else if(timeDiff / 1000 / 60 / 60 / 24 < 4)
			{
				period = timeDiff / 1000 / 60 / 60 /24;
				result = period + "天前";
			}
			else
			{
				sdf = new SimpleDateFormat("yyyy-MM-dd");
				result = sdf.format(date);
			}

		} catch (Throwable e) {
//			e.printStackTrace();
		}

		return result;
	}

    public static String calculateDateToNow(String date) {
		String d1 = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String result = null;
		try {
			Date date1 = sdf.parse(date);
            long timeDiff =  Math.abs(System.currentTimeMillis()  - date1.getTime());
            long period=0;

            period = timeDiff / 1000 / 60 / 60 /24;

            if(timeDiff / 1000 / 60 / 60 %  24 > 0)
            period++;

            result = String.valueOf(period);
          
		} catch (Exception e) {
            e.printStackTrace();
		}

		return result;
	}
	
	public static Timestamp calendar2Timestamp(Calendar cal){
		return new Timestamp(cal.getTimeInMillis());
	}
	
	public static Calendar date2Calendar(Date d){	
		Calendar cal=Calendar.getInstance();
		cal.setTime(d);
		return cal;
	}
	
	
	public static boolean compere(Date d1, Date d2, String type)
	{
		if(type.equals("date")){
			String pattern = "yyyy-MM-dd";
			String date1 = formatDate(d1, pattern);
			String date2 = formatDate(d2, pattern);
			//System.out.println(date1+date2);
			if(date1.equals(date2)){
				return true;
			}
			return false;
		}
		else
		{
			return d1.equals(d2);
		}
	}

     public static int compareDate(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    public static int compareToDate(Date date1,Date date2){
        if(date1.getTime() > date2.getTime()){
            return 1;
        }else if(date1.getTime() < date2.getTime()){
            return -1;
        }
        return 0;
    }

	
    public static String getSystemDateYYYYMMDDHHmmss() {
        SimpleDateFormat bartDateFormat =new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        return bartDateFormat.format(date);
    }

    /**
     * 获取天开始的时间
     *
     * @return
     */
    public static Date getTodayStart() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    /**
     * 得到几天前的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {  
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    public static Date getDateBeforeHour(Date d, int hour) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.HOUR, now.get(Calendar.HOUR) - hour);
        return now.getTime();
    }

    /**
     * 得到多少分钟之前的时间
     *
     * @param d
     * @param minute
     * @return
     */
    public static Date getDateBeforeMinute(Date d, int minute) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.add(Calendar.MINUTE, -minute);
        return now.getTime();
    }

    /**
     * 得到多少秒之前的时间
     *
     * @param d
     * @param second
     * @return
     */
    public static Date getDateBeforeMinutse(Date d, int second) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.add(Calendar.MINUTE,-second);
        return now.getTime();
    }


    /**
     * 得到几天后的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }


      public static Date getDateAfterHour(Date d, int hour) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.HOUR, now.get(Calendar.DATE) + hour);
        return now.getTime();
    }

	public static Date getDateAfterMinute(Date d, int minute) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.add(Calendar.MINUTE, minute);
		return now.getTime();
	}


    /**
     *
     * 方法描述：字符串日期转换
     * @param dateStr
     * @param pattern
     * @return
     * Date
     */
    public static Date parseDate(String dateStr,String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date=null;
        try {
            date= sdf.parse(dateStr);
        } catch (ParseException e) {
           
        }
        return date;
    }

    /**
     *
     * 方法描述：计算两个日期相隔天数<br/>
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     * int
     */
    public static int diffDay(Date smdate,Date bdate) {
        try{
            smdate = formatYMD(smdate);
            bdate = formatYMD(bdate);
            SimpleDateFormat sdf=new SimpleDateFormat(simpleFormat1);
            smdate=sdf.parse(sdf.format(smdate));
            bdate=sdf.parse(sdf.format(bdate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(bdate);
            long time2 = cal.getTimeInMillis();
            long between_days=(time2-time1)/(1000*3600*24);

            return Integer.parseInt(String.valueOf(between_days));
        }catch (Exception e) {
        	return 0;
        }
    }



    /**
     *
     * @param smdate
     * @param bdate
     * @return
     * @throws BaseException
     */
    public static double hourDiff(String smdate,String bdate){
         try{
             SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
             Date date1=df.parse(smdate);
             Date date2=df.parse(bdate);
             Calendar cal = Calendar.getInstance();
             cal.setTime(date1);
             long time1 = cal.getTimeInMillis();
             cal.setTime(date2);
             long time2 = cal.getTimeInMillis();
             double between_hours=(time2-time1)/(double)(1000*3600);

             return Double.parseDouble(String.valueOf(between_hours));
         }catch (Exception e) {
        	 return 0;
         }
     }


    public static double minuteDiff(Date smdate,Date bdate) {
           try{

               Calendar cal = Calendar.getInstance();
               cal.setTime(smdate);
               long time1 = cal.getTimeInMillis();
               cal.setTime(bdate);
               long time2 = cal.getTimeInMillis();
               double between_minute=(time2-time1)/(double)(1000*60);

               return Double.parseDouble(String.valueOf(between_minute));
           }catch (Exception e) {
        	   return 0;
           }
       }



    /**
     *
     * 方法描述：格式化时分秒<br/>
     * @return
     * Date
     */
    @SuppressWarnings("static-access")
    public static Date formatYMD(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(calendar.MINUTE,0);
        calendar.set(calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

	/**
	 *
	 * 方法描述：获取当前时间指定格式字符串<br/>
	 * @return
	 * String
	 */
	public static String getCurrentDateStr(String pattern) {
		SimpleDateFormat bartDateFormat =new SimpleDateFormat(pattern);
		Date date = new Date();
		return bartDateFormat.format(date);
	}

	/**
	 * 获取指定月份最开始的一天
	 * @param month 1代表1月,12代表12月份
	 * @return
	 */
	public static String getDayMinOfMonth(int month){
		Calendar cal = Calendar.getInstance();
		if(month == 12){
			cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)-1);
		}

		cal.set(Calendar.MONTH, month-1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DATE));
		return formatDate(cal.getTime(), simpleFormat1);
	}

	/**
	 * 获取指定月份最后的一天
	 * @param month 1代表1月,12代表12月份
	 * @return
	 */
	public static String getDayMaxOfMonth(int month){
		Calendar cal = Calendar.getInstance();
		if(month == 12){
			cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)-1);
		}

		cal.set(Calendar.MONTH, month-1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
		return formatDate(cal.getTime(),simpleFormat1);
	}

	public static Date stringParseDate(String dateStr,String pattern){
		SimpleDateFormat sdf =new SimpleDateFormat(pattern);
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
//			e.printStackTrace();
		}
		return date;
	}

	public static Date getDayStartOfMonth(int day){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_MONTH, day);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

    public static String getTImeDiff(String time1,String time2,String format) throws  Exception
    {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date1 = sdf.parse(time1);

        Date date2= sdf.parse(time2);

        long i = date2.getTime() - date1.getTime();
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(i);
        SimpleDateFormat f = new SimpleDateFormat(format);

        c.set(Calendar.HOUR, c.get(Calendar.HOUR) - 8);

        String time =  f.format(c.getTime());

      /*
        long between = (date2.getTime() - date1.getTime())/1000;

        long hour1=   between % (24*3600)/3600;
        long minute1= between % 3600/60;
        long second1= between % 60/60;

        String time =  hour1 + ":" + minute1 + ":" + second1;
        */
        return time;
    }

    public static String timestamp2StringMin(Timestamp time) {
		Date d = new Date(time.getTime());
		return DateFormatUtils.format(d, "yyyyMMddHHmm");
	}
    
    public static void main(String[] args){
////        System.out.println(getTodayStart().getTime());
////        System.out.println(new Date(1462420800000L));
////        String date1 = "2016-05-26 12:10:34";
////        String date2 = "2016-05-24 11:10:34";
////        System.out.println(compareDate(date1, date2));
//        Date date = new Date();
////        System.out.println(date.toLocaleString());
////        System.out.println(getDateBeforeSecond(date,60*30).toLocaleString());
//        System.out.println(DateUtils.formatDate(date,null));
//        Date beforeDate = DateUtils.getDateBeforeMinute(new Date(), 10);
//        System.out.println(DateUtils.formatDate(beforeDate,null));
//        System.out.println(compareToDate(date, beforeDate));
//
////        System.out.println(DateUtils.formatDate(date,null));
////        Calendar now = Calendar.getInstance();
////        now.setTime(date);
////        now.add(Calendar.SECOND, -600);
////        System.out.println(DateUtils.formatDate(now.getTime(), null));
//
//		System.out.println(getDayMin(getDayMinOfMonth(5)));
//		System.out.println(getDayMax(getDayMaxOfMonth(5)));
//
//		Date queryDate = string2Date("2016-11-04");
//		Date date1 = DateUtils.getDateAfter(queryDate, 30);
//		System.out.println(date1.toLocaleString());
//		System.out.println(DateUtils.compareToDate(new Date(), date1));
//
//		System.out.println(DateUtils.daysBetween(string2Date("2017-02-04"),new Date()));
    	
    	System.out.println(timestamp2StringMin(new Timestamp(System.currentTimeMillis())));
	}

	/**
	 * 计算两个日期之间相差的天数
	 * @param smdate 较小的时间
	 * @param bdate  较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate,Date bdate) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			smdate=sdf.parse(sdf.format(smdate));
			bdate=sdf.parse(sdf.format(bdate));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days=(time2-time1)/(1000*3600*24);

		return Integer.parseInt(String.valueOf(between_days));
	}

}
